
package com.scalar.chiptrack.operations.packingslip.actions;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.operations.packingslip.dao.CommercialInvoiceDAO;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.CommercialInvoiceForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;

public final class CommercialInvoiceAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/commercialInvoice.do";

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {


        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);

        HttpSession session = request.getSession();

        String action = request.getParameter ("action");
        User user = (User) session.getAttribute (SessionKeys.USER_KEY);
        if (user == null) {
            if( "showInvoice".equalsIgnoreCase( action ) == true )
            {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            }
            else
            {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME );
            }
            return (mapping.findForward ("login"));
        }


        CommercialInvoiceForm commercialInvoiceForm = (CommercialInvoiceForm) form;

        // Goes to Menu
        if( "loadPackingSlips".equalsIgnoreCase( action ) == true )
        {
            try
            {
                int salesOrderId = commercialInvoiceForm.getSalesOrderId();
                ArrayList packingSlipList = CommercialInvoiceDAO.loadPsBySoIdForUndeletedCommercialInvoices( salesOrderId );
                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );
				commercialInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );

				// Load the Client Information
				ClientInfo clientInfo = new ClientInfo();
				clientInfo = UserDAO.getClientAddressInfo(  );
				commercialInvoiceForm.setClientName( clientInfo.getClientName() );
                commercialInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                commercialInvoiceForm.setIsSample( salesOrder.getIsSample());

                request.setAttribute ("packingSlipList", packingSlipList);
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, "Error in loading Packingslips" );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_PACKING_SLIPS );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
                e.printStackTrace();
            }
        }

        // Delete the Commercial Invoice
        // Update a flag in Customer_Shipping_Table table
        if( "delete".equalsIgnoreCase( action ) == true )
        {
            int customerShippingId = -1;

            try
            {
                customerShippingId = commercialInvoiceForm.getCustomerShippingId();
                CommercialInvoiceDAO.deleteCommercialInovice( customerShippingId );
				int salesOrderId = commercialInvoiceForm.getSalesOrderId();
                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );
				commercialInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );

				// Load the Client Information
				ClientInfo clientInfo = new ClientInfo();
				clientInfo = UserDAO.getClientAddressInfo(  );
				commercialInvoiceForm.setClientName( clientInfo.getClientName() );
                commercialInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                commercialInvoiceForm.setIsSample( salesOrder.getIsSample());

                info.put( "Commercial Invoice has been deleted, successfully", null );
            }
            catch( Exception se )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_DELETING_COMMERCIAL_INVOICE + customerShippingId );
                se.printStackTrace();
                System.out.println( "Could not delete the invoice for Customer Shipping ID: " + customerShippingId );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_DELETING_COMMERCIAL_INVOICE + customerShippingId );
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
            }
        }

        // Save Commercial Invoice Information
        if( "save".equalsIgnoreCase( action ) == true )
        {
            try
            {
                CommercialInvoiceDAO.saveCommercialInvoice( commercialInvoiceForm, getLineItemScheduleNumberMap( request ) );
                info.put( "Commercial Invoice", "has been saved successfully" );
            }
            catch( Exception se )
            {
                se.printStackTrace();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_COMMERCIAL_INVOICE );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_SAVING_COMMERCIAL_INVOICE );
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
            }

            int salesOrderId = commercialInvoiceForm.getSalesOrderId();
            int customerShippingId = commercialInvoiceForm.getCustomerShippingId();

            Object[] result = null;
            try
            {
                result = getShippedLineItems( salesOrderId, customerShippingId );

                ArrayList lineItems = ( ArrayList ) result[0];
                request.setAttribute( "lineItems", lineItems );
                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );
                salesOrder.setSubTotalAsDouble( Double.parseDouble( ( String ) result[1] ) );

                float salesTaxValue = 0.0f;
                salesTaxValue = getSalesTaxValue(salesOrder);
                salesOrder.setSalesTaxValue(salesTaxValue);
                request.setAttribute( "salesOrder", salesOrder );

				commercialInvoiceForm =  CommercialInvoiceDAO.loadCommercialInvoice( customerShippingId );

                if ( commercialInvoiceForm.getBillingId() == -1 )
                {
                     //We are Assigning ShippingFromAddressId to  BillingAddressId because
                    //new column called  CST_Billing_Address_Id is added to CST table on 26 May 2004
                    //So Previously 'Billing Address' used to get from ShippingFromAddressId DB Field
                    //But now we are getting from For CST_Billing_Address_Id DB Field, so prvious PS records we fixed like this
                    commercialInvoiceForm.setBillingId(salesOrder.getBillingAddressId());
                }
                commercialInvoiceForm.setBillingAddressObject(CustomerDAO.getAddress( commercialInvoiceForm.getBillingId() ));
                commercialInvoiceForm.setBillingAddress( commercialInvoiceForm.getBillingAddressObject().getAddressAsString ( ) );

				commercialInvoiceForm.setSalesOrderId( salesOrder.getSalesOrderId() );
                commercialInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );

				// Load the Client Information
				ClientInfo clientInfo = new ClientInfo();
				clientInfo = UserDAO.getClientAddressInfo(  );
				commercialInvoiceForm.setClientName( clientInfo.getClientName() );
                commercialInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                commercialInvoiceForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress( commercialInvoiceForm.getVendorLocationId() ) );

            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
                e.printStackTrace();
            }

            request.setAttribute( "commercialInvoiceForm", commercialInvoiceForm );

            if( "yes".equalsIgnoreCase( request.getParameter( "fromEmailPS" ) ) )
            {
                return( mapping.findForward( "edit" ) );
            }
            return( mapping.findForward( "invoice" ) );
        }

        // added new deleteConfirm action
        if ( ( "loadInvoice".equalsIgnoreCase( action ) == true ) || ( "deleteConfirm".equalsIgnoreCase( action ) == true ) )
        {
            String retVal = "invoice";

            int salesOrderId = -1;
            int customerShippingId = -1;
            //int locationId  = -1;

            if( "yes".equalsIgnoreCase( request.getParameter( "fromEmailPS" ) ) )
            {
                try
                {
                    salesOrderId = Integer.parseInt( request.getParameter( "salesOrderId" ) );
                    customerShippingId = Integer.parseInt( request.getParameter( "customerShippingId" ) );
                    if ( NewPackingSlipDAO.isShippingIdCancelled( customerShippingId ) )
                    {
                        retVal = "view";
                    }
                    else
                    {
                        retVal = "edit";
                    }
                }
                catch( NumberFormatException nfe ){}
            }
            else
            {
                salesOrderId = commercialInvoiceForm.getSalesOrderId();
                customerShippingId = commercialInvoiceForm.getCustomerShippingId();
            }

            try
            {
                Object[] result = getShippedLineItems (salesOrderId, customerShippingId);

                ArrayList lineItems = (ArrayList) result[0];
                request.setAttribute ("lineItems", lineItems);

                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder (salesOrderId+"");
                salesOrder.setSubTotalAsDouble( Double.parseDouble( ( String ) result[1] ) );
				commercialInvoiceForm.setContactPerson (salesOrder.getShippingAddressAsObject().getContactPerson() );
				commercialInvoiceForm.setShippingAddress ( salesOrder.getShippingAddressAsObject() );

                float salesTaxValue = 0.0f;
                salesTaxValue = getSalesTaxValue(salesOrder);
                salesOrder.setSalesTaxValue(salesTaxValue);

                request.setAttribute( "salesOrder", salesOrder );
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
                e.printStackTrace();
            }

            try
            {
				CommercialInvoiceForm cInvoiceForm = CommercialInvoiceDAO.loadCommercialInvoice( customerShippingId );
    	        cInvoiceForm.setSalesOrderId( salesOrderId );
				SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder (salesOrderId+"");

                if ( cInvoiceForm.getBillingId() == -1 )
                {
                     //We are Assigning ShippingFromAddressId to  BillingAddressId because
                    //new column called  CST_Billing_Address_Id is added to CST table on 26 May 2004
                    //So Previously 'Billing Address' used to get from ShippingFromAddressId DB Field
                    //But now we are getting from For CST_Billing_Address_Id DB Field, so prvious PS records we fixed like this
                    cInvoiceForm.setBillingId(salesOrder.getBillingAddressId());
                }

                cInvoiceForm.setBillingAddressObject(CustomerDAO.getAddress( cInvoiceForm.getBillingId() ));
                cInvoiceForm.setBillingAddress( cInvoiceForm.getBillingAddressObject().getAddressAsString () );
				cInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );
                cInvoiceForm.setIsSample( salesOrder.getIsSample());

				// Load the Client Information
				ClientInfo clientInfo = new ClientInfo();
				clientInfo = UserDAO.getClientAddressInfo(  );
				cInvoiceForm.setClientName( clientInfo.getClientName() );
                cInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                cInvoiceForm.setIsSample( salesOrder.getIsSample());
                cInvoiceForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress( cInvoiceForm.getVendorLocationId() ) );
                request.setAttribute( "commercialInvoiceForm", cInvoiceForm );
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_COMMERCIAL_INVOICE_FOR_CUSTOMER_SHIPPING_ID + customerShippingId );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_COMMERCIAL_INVOICE_FOR_CUSTOMER_SHIPPING_ID + customerShippingId );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );

                e.printStackTrace();
            }

            return( mapping.findForward( retVal ) );
        }

        // new pop-up window
        if( "showInvoice".equalsIgnoreCase( action ) == true )
        {
            int salesOrderId 		= -1;
            int customerShippingId 	= -1;
            boolean success 		= false;
			ClientInfo clientInfo = new ClientInfo();

            try
            {
                salesOrderId 		= Integer.parseInt ( request.getParameter ( "salesOrderId" ) );
                customerShippingId 	= Integer.parseInt ( request.getParameter ( "customerShippingId" ) );
                success = true;
            }
            catch (NumberFormatException nfe)
            {
                nfe.printStackTrace();
            }

            if ( success == true )
            {
                try
                {
                    Object[] result 	= getShippedLineItems ( salesOrderId, customerShippingId );
                    ArrayList lineItems = (ArrayList) result[0];

                    request.setAttribute ( "lineItems", lineItems );

                    SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder (salesOrderId+"");
                    salesOrder.setSubTotalAsDouble(Double.parseDouble((String) result[1]));
                    float salesTaxValue = 0.0f;
                    salesTaxValue = getSalesTaxValue(salesOrder);
                    salesOrder.setSalesTaxValue(salesTaxValue);

                    request.setAttribute ("salesOrder", salesOrder);
                }
                catch( Exception e )
                {
                    errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                    errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_LINE_ITEMS_FOR_SALES_ORDER_ID + salesOrderId );
                    session.setAttribute( SessionKeys.ERROR_REPORT, e );
                    e.printStackTrace();
                }

                try
                {
                    CommercialInvoiceForm cInvoiceForm = CommercialInvoiceDAO.loadCommercialInvoice( customerShippingId );
                    cInvoiceForm.setSalesOrderId( salesOrderId );
                    SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );
                    if ( cInvoiceForm.getBillingId() == -1 )
                    {
                         //We are Assigning ShippingFromAddressId to  BillingAddressId because
                        //new column called  CST_Billing_Address_Id is added to CST table on 26 May 2004
                        //So Previously 'Billing Address' used to get from ShippingFromAddressId DB Field
                        //But now we are getting from For CST_Billing_Address_Id DB Field, so prvious PS records we fixed like this
                        cInvoiceForm.setBillingId(salesOrder.getBillingAddressId());
                    }
                    cInvoiceForm.setBillingAddressObject(CustomerDAO.getAddress( cInvoiceForm.getBillingId() ));
                    cInvoiceForm.setBillingAddress( cInvoiceForm.getBillingAddressObject().getAddressAsString ( ) );
				    cInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );
                    cInvoiceForm.setIsSample( salesOrder.getIsSample());
                    cInvoiceForm.setShippingTerms( salesOrder.getShippingTerms() );

					clientInfo = UserDAO.getClientAddressInfo();
					cInvoiceForm.setClientName(clientInfo.getClientName());
					cInvoiceForm.setClientInfo( clientInfo );
                    cInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                    cInvoiceForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress( cInvoiceForm.getVendorLocationId() ) );

                    request.setAttribute( "commercialInvoiceForm", cInvoiceForm );
                }
                catch( Exception e )
                {
                    errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_COMMERCIAL_INVOICE_FOR_CUSTOMER_SHIPPING_ID + customerShippingId );
                    errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_COMMERCIAL_INVOICE_FOR_CUSTOMER_SHIPPING_ID + customerShippingId );
                    session.setAttribute( SessionKeys.ERROR_REPORT, e );
                    e.printStackTrace();
                }
            }
            //Added by varma to show the terms and conditions in PF versions
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
            if( Constants.CLIENT_NAME_AIRGO.equalsIgnoreCase( clientInfo.getClientName() ) )
            {
                return ( mapping.findForward ( "printViewAirgo" ) );
            }
            else
            {
                return (mapping.findForward ("view"));
            }
        }

        // Default - Show Commercial Invoice Menu
        try
        {
            request.setAttribute( "salesOrderList", CommercialInvoiceDAO.loadSalesOrderIdAndNumberList() );
        }
        catch( Exception e )
        {
            errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_SALES_ORDER_NUMBERS );
            errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
            session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_SALES_ORDER_NUMBERS );
            session.setAttribute( SessionKeys.ERROR_REPORT, e );
            e.printStackTrace();
        }

        try
        {
            request.setAttribute( "salesOrdercustomerPOList", CommercialInvoiceDAO.loadSalesOrderCustomerPOList() );
        }
        catch( Exception e )
        {
            errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_CUSTOMER_PO_NUMBERS );
            errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
            session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_CUSTOMER_PO_NUMBERS );
            session.setAttribute( SessionKeys.ERROR_REPORT, e );
            e.printStackTrace();
        }

        return( mapping.findForward( "menu" ) );
    }


    public static Object[] getShippedLineItems( int salesOrderId, int customerShippingId ) throws ScalarException
    {
        //HashMap lineItemMap 		= SalesOrderDAO.loadOrderLineItemsMap ( salesOrderId );    modified by sujan on 29th nov 2004 as we need to load the sw lineitems which r cancelled also
        HashMap lineItemMap = null;
        if ( NewPackingSlipDAO.isSoftWareSalesOrder( salesOrderId ) )
        {
            lineItemMap 	= SalesOrderDAO.loadOrderLineItemsMapWithCancelledLineItems ( salesOrderId );
        }
        else
        {
            lineItemMap     = SalesOrderDAO.loadOrderLineItemsMap ( salesOrderId );
        }
        HashMap shippedLineItemMap 	= PackingSlipDAO.loadCustomerShippingLineItemQuantityById (customerShippingId);

        java.util.Set keySet = shippedLineItemMap.keySet();
        Object[] arrayKeySet = keySet.toArray();
        java.util.Arrays.sort( arrayKeySet );
        int length = arrayKeySet.length;

        ArrayList resultLineItems = new ArrayList();
        LineItem lineItem = null;
		String lineItemId = null;
        int quantity 	= 0;
        double amount 	= 0.0f;
        double subtotal 	= 0.0f;
        int zeroPriceTotalQty = 0;
        for( int i = 0; i < length ; i++ )
        {
            lineItemId 	= ( String ) arrayKeySet[i];
            lineItem 	= ( LineItem ) lineItemMap.get ( lineItemId );

            if ( lineItem != null )
            {
                quantity = Integer.parseInt ( ( String ) shippedLineItemMap.get ( lineItemId ) );
                amount = quantity*lineItem.getUnitPriceAsDouble();
                subtotal += amount;
                lineItem.setQuantity ( quantity );
                lineItem.setAmountAsDouble ( amount );

				// Load Line Item Details like ECCN, HTS, UOM, Description, ScheduleNumber etc
				NewPackingSlipDAO.getLineItemScheduleNumberAndDescription( lineItem, customerShippingId );
                /*CommercialInvoiceDAO.getFabCountryOfOrigin( lineItem);
                CommercialInvoiceDAO.getAssemblyCountryOfOrigin( lineItem );*/



                /*String[] scheduleNumberAndDescription = NewPackingSlipDAO.getLineItemScheduleNumberAndDescription( lineItem, customerShippingId );

                if( ( scheduleNumberAndDescription != null ) && ( scheduleNumberAndDescription.length == 3 ) )
                {
                    lineItem.setScheduleNumber( scheduleNumberAndDescription[0] );
                    if( ( scheduleNumberAndDescription[1] != null ) && ( scheduleNumberAndDescription[1].trim().length() != 0 ) )
                    {
                        lineItem.setDescription( scheduleNumberAndDescription[1] );
                    }
					if( ( scheduleNumberAndDescription[2] != null ) && ( scheduleNumberAndDescription[2].trim().length() != 0 ) )
					{
						lineItem.setCustomerPartNumber( scheduleNumberAndDescription[2] );
					}
                }*/
                if ( lineItem.getUnitPriceAsDouble() == 0 )
                {
                    zeroPriceTotalQty += quantity;
                }
                resultLineItems.add (lineItem);
            }
        }

		/*if( subtotal == 0.0f )
		{
			Object[] result = setMinPrice( resultLineItems );
			resultLineItems = (ArrayList) result[0];
			subtotal = Double.parseDouble((String)result[1]);
		}*/
        if ( zeroPriceTotalQty > 0 ) //there are line items with zero price
        {
            Object[] result = adjustLineItemPrice( resultLineItems, zeroPriceTotalQty, subtotal );
            resultLineItems = (ArrayList) result[0];
			subtotal = Double.parseDouble((String)result[1]);
        }

        Collections.sort(resultLineItems,new PackingSlipComparator());
        return new Object[] {resultLineItems, subtotal+""};
    }

    /**
     * @param resultLineItems
     * @return Object[]
     */
    private static Object[] setMinPrice( ArrayList resultLineItems ) throws ScalarException
    {
    	HashMap commercialSettings = CommercialInvoiceDAO.loadCommercialInvoiceSettings();

    	String flag = (String)commercialSettings.get( "Adjust_Flag" );
		LineItem lineItem = null;

        float max_unit_price  = 0.0f;
        if( commercialSettings.get("Max_Unit_Price") != null )
        {
		    max_unit_price 	= ((Float)commercialSettings.get("Max_Unit_Price")).floatValue();
        }

		float subTotal = 0.0f;
    	if( "1".equals( flag) )
    	{
    		for ( int i = 0; i < resultLineItems.size(); i++ )
    		{
				lineItem = (LineItem)resultLineItems.get(i);
				lineItem.getQuantity();
				lineItem.getUnitPriceAsDouble();
				lineItem.getAmount();

				if( lineItem.getUnitPriceAsDouble() == 0 && lineItem.getQuantity() > 0 )
				{
					if( lineItem.getQuantity() > 10 )
					{
						lineItem.setUnitPriceAsDouble( max_unit_price );
						lineItem.setAmountAsDouble( lineItem.getUnitPriceAsDouble() * lineItem.getQuantity() );
					}
					else
					{
						lineItem.setUnitPriceAsDouble( (1.0f/lineItem.getQuantity()) );
						lineItem.setAmountAsDouble( lineItem.getUnitPriceAsDouble() * lineItem.getQuantity() );
					}
					subTotal +=  lineItem.getUnitPriceAsDouble() * lineItem.getQuantity();
				}
			}
    	}
        return new Object[]{resultLineItems, subTotal+""};
    }


    private HashMap getLineItemScheduleNumberMap( HttpServletRequest request )
    {
        HashMap lineItemScheduleNumberMap = new HashMap();

        int lineItemListSize = -1;
        try
        {
            lineItemListSize = Integer.parseInt( request.getParameter( "lineItemListSize" ) );
        }
        catch( NumberFormatException nfe )
        {
        }

        for( int i=0; i<lineItemListSize; i++ )
        {
            lineItemScheduleNumberMap.put( request.getParameter( "lineItemId_" + i ), request.getParameter( "scheduleNumber_" + i ) );
        }

        return lineItemScheduleNumberMap;
    }

    public static String getCommercialInvoiceAsPDFFile ( String salesOrderIdStr, String customerShippingIdStr, String host, String packingSlipLabel ) throws ScalarException
    {

        String fileXMLPath 		= null;
		String filePDFPath 		= null;
		FileWriter fWriter 		= null;
        OutputStreamWriter out  = null;
        String ciAsXML 			= formatAsXML( salesOrderIdStr, customerShippingIdStr, host );

		if( ciAsXML == null )
		{
			return fileXMLPath;
		}

		try
		{
            String xsltFileName = ConfigManager.getCommercialInvoiceXml2PdfXslFile();
            
            String mailingTempDir 		= ConfigManager.getMailerTempDir();
			File tempDir 				= new File ( mailingTempDir ).getCanonicalFile();
            tempDir.mkdir();

            String ciAttachmentFileName = packingSlipLabel;
            String ciXmlFileName = "";
            if( ( ciAttachmentFileName != null ) && ( ciAttachmentFileName.startsWith( "PS-" ) ) )
            {
                ciAttachmentFileName =  ciAttachmentFileName.substring( 3 );

            }
            ciXmlFileName =  ciAttachmentFileName;
            ciAttachmentFileName = "Commercial_Invoice_SO_" + ciAttachmentFileName + ".pdf";
            ciXmlFileName = "Commercial_Invoice_SO_" + ciXmlFileName + ".xml";


			File ciAttachment = new File( tempDir.getCanonicalPath(), ciAttachmentFileName );
            ciAttachment.deleteOnExit();

            File ciXml = new File( tempDir.getCanonicalPath(), ciXmlFileName );
            ciXml.deleteOnExit();

			if( ( ciXml.exists() == true ) || ( ciXml.createNewFile() == true ) )
			{
				/*fWriter = new FileWriter ( psXML, false);
				fWriter.write ( psAsXML );
				fWriter.close();
				fWriter = null*/;

                out = new OutputStreamWriter( new FileOutputStream( ciXml ), "UTF-8" );

                out.write ( ciAsXML );
                out.close ();
                out = null;


                fileXMLPath = ciXml .getCanonicalPath() .toLowerCase();
				filePDFPath = ciAttachment .getCanonicalPath() .toLowerCase();
				boolean success = PDFGenerator.convertXML2PDF( fileXMLPath, xsltFileName, filePDFPath );
			}
		}
		catch( Exception e )
		{
			System.out.println( "Exception while creating commercial Invoice PDF file");
			e.printStackTrace();
		}
		finally
		{
			if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
            if( out != null )
			{
				try
				{
					out.close();
					out = null;
				}
				catch( IOException ignore ){}
			}
        }
        return filePDFPath;
    }

    public static String formatAsXML ( String salesOrderIdStr, String customerShippingIdStr, String host )
    {
		StringBuffer buf = new StringBuffer ( 2098 );
        int salesOrderId = -1;
        int customerShippingId = -1;
        boolean success = false;
		String MFG_PART_NUMBER_KEY = "";
		String MKT_PART_NUMBER_KEY = "";
		String SCHEDULE_NUMBER_KEY	= "";
		String ECCN_NUMBER_KEY	= "";
		String LICENSE_EXCEPTION_KEY	= "";
        String WEIGHT_MEASUREMENT = "";
        String SCHEDULE_NUMBER_DESCRIPTION_KEY = "";
        String COMMERCIAL_INVOICE_NO = "";
        String SIGNATURE = "";
        try
        {
            try
            {
                 WEIGHT_MEASUREMENT = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.WeightMeasurements" );
            }
            catch ( NullPointerException e )
            {
                 WEIGHT_MEASUREMENT = Labels.DEFAULT_WEIGHT_MEASUREMENT_LABEL;
            }

            try
            {
                 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mfgPartNumber");
            }
            catch ( NullPointerException e )
            {
                 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
            }
            try
            {
                 MKT_PART_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mktgPartNumber");
            }
            catch ( NullPointerException e )
            {
                 MKT_PART_NUMBER_KEY = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
            }

            try
            {
                SCHEDULE_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ScheduleNumber");
            }
            catch ( NullPointerException e )
            {
                SCHEDULE_NUMBER_KEY = Labels.DEFAULT_SCHEDULE_NUMBER_LABEL;
            }

            try
            {
                SCHEDULE_NUMBER_DESCRIPTION_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ScheduleNumberDiscription");
            }
            catch ( NullPointerException e )
            {
                SCHEDULE_NUMBER_DESCRIPTION_KEY = Labels.DEFAULT_SCHEDULE_NUMBER_DESCRIPTION_LABEL;
            }

            try
            {
                ECCN_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ECCN");
            }
            catch ( NullPointerException e )
            {
                ECCN_NUMBER_KEY = Labels.DEFAULT_ECCN_NUMBER_LABEL;
            }

            try
            {
                LICENSE_EXCEPTION_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.LicenseSymbol");
            }
            catch ( NullPointerException e )
            {
                LICENSE_EXCEPTION_KEY = Labels.DEFAULT_LICENSE_EXCEPTION_LABEL;
            }
            try
            {
                 COMMERCIAL_INVOICE_NO = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.commercialInvoice.commercialInvoiceNo" );
            }
            catch ( NullPointerException e )
            {
                COMMERCIAL_INVOICE_NO =  "";
            }
            try
            {
                 SIGNATURE = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.signature" );
            }
            catch ( NullPointerException e )
            {
                SIGNATURE =  Labels.DEFAULT_SIGNATURE_LABEL;
            }

            try
            {
                salesOrderId = Integer.parseInt ( salesOrderIdStr );
                customerShippingId = Integer.parseInt ( customerShippingIdStr );

                success = true;
            }
            catch (NumberFormatException nfe) {
                nfe.printStackTrace();
            }

            try
            {
                salesOrderId = Integer.parseInt ( salesOrderIdStr );
                customerShippingId = Integer.parseInt ( customerShippingIdStr );

                success = true;
            }
            catch (NumberFormatException nfe) {
                nfe.printStackTrace();
            }


            SalesOrder salesOrder = null;
            ArrayList lineItemList = new ArrayList();
            CommercialInvoiceForm commercialInvoiceForm = new CommercialInvoiceForm();
            Address billingAddress = null;
            Address shippingAddress = null;
            Address shipperAddress = null;

            if (success == true)
            {
                Object[] result = getShippedLineItems (salesOrderId, customerShippingId);

                lineItemList = (ArrayList) result[0];

                salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );

                if( salesOrder != null )
                {
                    salesOrder.setSubTotalAsDouble (Double.parseDouble((String) result[1]));
                    float salesTaxValue = 0.0f;
                    salesTaxValue = getSalesTaxValue(salesOrder);
                    salesOrder.setSalesTaxValue(salesTaxValue);
                }

                commercialInvoiceForm = CommercialInvoiceDAO.loadCommercialInvoice( customerShippingId );

                if ( commercialInvoiceForm.getBillingId() == -1 )
                {
                    commercialInvoiceForm.setBillingId(salesOrder.getBillingAddressId());
                }
                commercialInvoiceForm.setBillingAddressObject(CustomerDAO.getAddress( commercialInvoiceForm.getBillingId() ));
                commercialInvoiceForm.setBillingAddress( commercialInvoiceForm.getBillingAddressObject().getAddressAsString ( ) );
                commercialInvoiceForm.setIsSample( salesOrder.getIsSample());
                commercialInvoiceForm.setShippingTerms( salesOrder.getShippingTerms() );

                commercialInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );
                // Load the Client Information
                ClientInfo clientInfo = new ClientInfo();
                clientInfo = UserDAO.getClientAddressInfo(  );
                commercialInvoiceForm.setClientName( clientInfo.getClientName() );
                commercialInvoiceForm.setClientInfo(clientInfo);
                commercialInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
                commercialInvoiceForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress( commercialInvoiceForm.getVendorLocationId() ));
                if( commercialInvoiceForm != null )
                {
                    commercialInvoiceForm.setSalesOrderId( salesOrderId );
                    shipperAddress = commercialInvoiceForm.getShipperAddressObject();
                    billingAddress = commercialInvoiceForm.getBillingAddressObject();
                    shippingAddress= commercialInvoiceForm.getShippingAddressObject();
                }
            }

            if( salesOrder == null )
            {
                return null;
            }

            buf.append ( "<?xml version='1.0' encoding='UTF-8'?>\n" );
            if (Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase (commercialInvoiceForm.getStatus())) {
                buf.append( "<commercialInvoice cancel='1'>\n" );
            }else{
                buf.append( "<commercialInvoice cancel='0'>\n" );
            }

            buf.append ( "<salesOrderFieldHeading>");
            if( commercialInvoiceForm.getIsSample())
            {
                buf.append("Sample Sales Order#:");
            }
            else
            {
                buf.append("Sales Order#:");
            }
            buf.append( "</salesOrderFieldHeading>\n");

            buf.append ( "<commercialInvoiceHeading>");
            buf.append(COMMERCIAL_INVOICE_NO + ":");
            buf.append( "</commercialInvoiceHeading>");

            buf.append ( "<signature>");
            buf.append( SIGNATURE );
            buf.append( "</signature>");

            String imagesDirLocation = ConfigManager.getChipTracImagesDir();
            String scalarLogo = ConfigManager.getScalarLogo();
            String crossCancel = ConfigManager.getCrossCanelImage();
            
            buf.append ( "<images>\n");
            buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
            buf.append ( "<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n ");
            buf.append ( "</images>\n");
            buf.append ( "<selfAddress> \n" );
            buf.append ( "<name><![CDATA[" + commercialInvoiceForm.getClientInfo().getClientName() + "]]></name> \n" );
            buf.append ( commercialInvoiceForm.getClientAddressXMLFormatted() );
            buf.append ( "</selfAddress> \n" );
            buf.append ( "<shipperAddress>\n" );

            buf.append ( "<name><![CDATA[" /*+ commercialInvoiceForm.getClientName() + " c/o "*/ + ( ( commercialInvoiceForm.getClientName() == null) ? "" : commercialInvoiceForm.getClientName() ) + "]]></name>\n" );
            buf.append ( commercialInvoiceForm.convertVendorAddressObjToXml( commercialInvoiceForm.getShippingVendorAddressObject()) );

            buf.append ( "</shipperAddress>\n" );

            buf.append ( "<billToAddress>\n" );

            buf.append ( commercialInvoiceForm.convertAddressObjToXml( billingAddress, salesOrder.getCustomerName() ) );

            buf.append ( "</billToAddress>\n" );

            buf.append ( "<shipToAddress>\n" );

            buf.append ( commercialInvoiceForm.convertAddressObjToXml( shippingAddress, salesOrder.getCustomerName() ) );

            buf.append ( "</shipToAddress>\n" );

            buf.append ( "<information>\n" );
            buf.append( "<salesOrder><![CDATA[" + salesOrder.getSalesOrderNo() + "]]></salesOrder>\n" );
            buf.append( "<shipDate><![CDATA[" + (commercialInvoiceForm.getShipDate() == null ? "" : commercialInvoiceForm.getShipDate()) + "]]></shipDate>\n" );
            buf.append( "<shippingTerms><![CDATA[" + commercialInvoiceForm.getShippingTerms() + "]]> </shippingTerms>\n" );
            buf.append( "<packingSlip><![CDATA[" + commercialInvoiceForm.getPackingSlipNumber() + "]]></packingSlip>\n" );
            buf.append( "<commercialInvoiceNo><![CDATA[" + commercialInvoiceForm.getCommercialInvoiceNo() + "]]></commercialInvoiceNo>\n" );
            buf.append( "<customerPO><![CDATA[" + ( ( ( salesOrder.getCustomerPO() == null ) || ( salesOrder.getCustomerPO() != null && salesOrder.getCustomerPO().trim().length() == 0 ) ) ? "" : salesOrder.getCustomerPO() ) + "]]></customerPO>\n" );

            String deliveryTerms = commercialInvoiceForm.getFob();
            deliveryTerms = ( ( ( deliveryTerms == null )  || ( deliveryTerms != null && deliveryTerms.trim().length() == 0 ) ) ? "" : deliveryTerms );

            String fabOriginCountry = commercialInvoiceForm.getCountryOfFabOrigin();
            fabOriginCountry = ( ( ( fabOriginCountry == null )  || ( fabOriginCountry != null && fabOriginCountry.trim().length() == 0 ) ) ? "" : fabOriginCountry );

            String assyOriginCountry = commercialInvoiceForm.getCountryOfAssyOrigin();
            assyOriginCountry = ( ( ( assyOriginCountry == null )  || ( assyOriginCountry != null && assyOriginCountry.trim().length() == 0 ) ) ? "" : assyOriginCountry );

           /* String landingPort = commercialInvoiceForm.getPortOfLanding();
            landingPort = ( ( ( landingPort == null )  || ( landingPort != null && landingPort.trim().length() == 0 ) ) ? "" : landingPort );

            String destinationPort = commercialInvoiceForm.getPortOfDestination();
            destinationPort = ( ( ( destinationPort == null )  || ( destinationPort != null && destinationPort.trim().length() == 0 ) ) ? "" : destinationPort );*/

            String comments = commercialInvoiceForm.getComments();
            comments = ( ( ( comments == null )  || ( comments != null && comments.trim().length() == 0 ) ) ? "" : comments );

            if( commercialInvoiceForm.getFrieghtTrackingNumber() != null && commercialInvoiceForm.getFrieghtTrackingNumber().length > 0 )
            {
                for ( int i = 0; i < commercialInvoiceForm.getFrieghtTrackingNumber().length; i++ )
                {
                    buf.append( "<freightTracking>\n");
                    buf.append( "<tracking>\n<![CDATA[" );
                    buf.append( commercialInvoiceForm.getFrieghtTrackingNumber()[i] );
                    buf.append( "]]></tracking>\n" );
                    buf.append( "</freightTracking> \n" );
                }
            }
            else
            {
                buf.append( "<freightTracking>\n");
                buf.append( "<tracking>\n<![CDATA[]]></tracking> \n" );
                buf.append( "</freightTracking> \n" );
            }

            buf.append( "<incoterms><![CDATA[" + deliveryTerms + "]]></incoterms>\n" );
            buf.append( "<countryOfFabOrigin><![CDATA[" + fabOriginCountry + "]]></countryOfFabOrigin>\n" );
            buf.append( "<countryOfAssyOrigin><![CDATA[" + assyOriginCountry + "]]></countryOfAssyOrigin>\n" );
            /*buf.append( "<loadingPort><![CDATA[" + landingPort + "]]></loadingPort>\n" );
            buf.append( "<destinationPort><![CDATA[" + destinationPort + "]]></destinationPort>\n" );*/
            buf.append( "<comments><![CDATA[" + comments + "]]></comments>\n" );
            buf.append ( "</information>\n" );


            buf.append( "<lineItems>\n" );

            buf.append ( "<mfgPartTitle><![CDATA[");
            buf.append ( MFG_PART_NUMBER_KEY );
            buf.append ( "]]></mfgPartTitle> \n" );
            buf.append ( "<mktPartTitle><![CDATA[");
            buf.append ( MKT_PART_NUMBER_KEY );
            buf.append ( "]]></mktPartTitle> \n" );

            buf.append ( "<scheduleTitle><![CDATA[");
            buf.append ( SCHEDULE_NUMBER_KEY );
            buf.append ( "]]></scheduleTitle> \n" );

            buf.append ( "<scheduleNoDes><![CDATA[");
            buf.append ( SCHEDULE_NUMBER_DESCRIPTION_KEY );
            buf.append ( "]]></scheduleNoDes> \n" );

            buf.append ( "<eccnTitle><![CDATA[");
            buf.append ( ECCN_NUMBER_KEY );
            buf.append ( "]]></eccnTitle> \n" );

            buf.append ( "<licenseExceptionTitle><![CDATA[");
            buf.append ( LICENSE_EXCEPTION_KEY );
            buf.append ( "]]></licenseExceptionTitle> \n" );

            float totalSalesTaxValue = 0f;
            float salesTaxValue = salesOrder.getSalesTaxValue();

            if( ( lineItemList != null ) && ( lineItemList.size() != 0 ) )
            {
                int lineItemListSize = lineItemList.size();
                LineItem lineItem = null;
                int poLineItem = -1;
                String mktPartNumber = null;
                String mfgPartNumber = null;
                String custPartNumber = null;
                String description = null;
                String scheduleNumber = null;
                String qty = null;
                String unitPrice = null;
                String amount = null;
                String eccn = null;
                String licenseException = null;
                String uom = null;
                String scheduleDescription = null;

                for( int i = 0; i <= ( lineItemListSize-1 ); i++ )
                {

                    lineItem = ( LineItem ) lineItemList.get( i );

                    poLineItem = lineItem.getPoLineItemNo();

                    if(lineItem.getIsTaxable()){
                        totalSalesTaxValue += lineItem.getAmount();
                    }

                    mfgPartNumber = lineItem.getManufacturingPartNo();
                    mktPartNumber = lineItem.getMarketingPartNo();
                    if( ( mktPartNumber == null ) || (  mktPartNumber != null && mktPartNumber.trim().length() == 0 ) ) { mktPartNumber = ""; }
                     if( ( mfgPartNumber == null ) || (  mfgPartNumber != null && mfgPartNumber.trim().length() == 0 ) ) { mfgPartNumber = ""; }

                    custPartNumber = lineItem.getCustomerPartNumber();
                    if( ( custPartNumber == null ) || ( custPartNumber != null && custPartNumber.trim().length() == 0 ) ) { custPartNumber = ""; }

                    description = lineItem.getDescription();
                    if( ( description == null ) || ( description != null && description.trim().length() == 0 ) ) { description = ""; }
                    else { description = description.trim(); }

                    scheduleNumber = lineItem.getScheduleNumber();

                    if( ( scheduleNumber == null ) || ( scheduleNumber != null && scheduleNumber.equalsIgnoreCase("null") ) || ( scheduleNumber != null &&  scheduleNumber.trim().length() == 0 ) ) { scheduleNumber = ""; }
                    // This peice of code is kept because before they are storing an &nbsp; value as default
                    // for Schedule number this is throwing an exception
                    if( scheduleNumber.length() == 1 )
                    {
                        if( Character.getNumericValue((char)scheduleNumber.getBytes()[0] ) == -1)
                        {
                            scheduleNumber = "";
                        }
                    }

                    scheduleDescription = ( lineItem.getScheduleDescription() == null )? "":lineItem.getScheduleDescription();

                    eccn = ( lineItem.getEccn() == null )? "":lineItem.getEccn();

                    licenseException = ( lineItem.getLicenseException() == null )?"":lineItem.getLicenseException();
                    uom = ( lineItem.getUom() == null )? "":lineItem.getUom();

                    qty = lineItem.getQtyAsString();
                    if( ( qty == null ) || ( qty != null && qty.trim().length() == 0 ) ) { qty = ""; }

                    amount = lineItem.getAmountAsString();
                    if( ( amount == null ) || ( amount != null && amount.trim().length() == 0 ) ) { amount = ""; }

                    unitPrice = lineItem.getDisplayUnitPrice();
                    if( ( unitPrice == null ) || (  unitPrice != null && unitPrice.trim().length() == 0 ) ) { unitPrice = ""; }

                    buf.append( "<lineItem>\n" );
                    buf.append( "<poLineNumber><![CDATA[" + ( poLineItem < 1 ? "" : poLineItem+"" ) + "]]></poLineNumber>\n" );
                    buf.append( "<mktPartNunber><![CDATA[" + mktPartNumber + "]]></mktPartNunber>\n" );
                    buf.append( "<mfgPartNunber><![CDATA[" + mfgPartNumber + "]]></mfgPartNunber>\n" );
                    buf.append( "<customerPartNumber><![CDATA[" + custPartNumber + "]]></customerPartNumber>\n" );
                    buf.append( "<productDescription><![CDATA[" + description + "]]></productDescription>\n" );
                    buf.append( "<uom><![CDATA["+uom+"]]></uom>\n" );
                    buf.append( "<scheduleNumber><![CDATA["+scheduleNumber+"]]></scheduleNumber>\n" );
                    buf.append( "<scheduleNumberDescription><![CDATA["+scheduleDescription+"]]></scheduleNumberDescription>\n" );
                    buf.append( "<eccn><![CDATA["+eccn+"]]></eccn>\n" );
                    buf.append( "<licenseException><![CDATA["+licenseException+"]]></licenseException>\n" );
                    buf.append( "<shippedQty><![CDATA[" + qty + "]]></shippedQty>\n" );
                    buf.append( "<unitPrice><![CDATA[" + unitPrice + "]]></unitPrice>\n" );
                    buf.append( "<lineTotal><![CDATA[" + amount + "]]></lineTotal>\n" );
                    buf.append( "</lineItem>\n" );
                }
            }
            buf.append( "</lineItems>\n" );
            buf.append( "<extInformation>\n" );

            String totalPackages = commercialInvoiceForm.getTotalPackagesStr()+"";
            totalPackages = ( ( ( totalPackages == null )  || ( totalPackages != null && totalPackages.trim().length() == 0 ) ) ? "" : totalPackages );

            String totalWeight  = commercialInvoiceForm.getTotalWeight()+"";
            String weightType   = commercialInvoiceForm.getWeightType();
            String weightLabel  = "";
            if( ConfigManager.getShowPackageDimensionInPackingSlip() )
            {
                weightLabel = "NET WEIGHT";
            }
            else
            {
                weightLabel = "WEIGHT";
            }

            WEIGHT_MEASUREMENT = ( ( ( totalWeight == null )  || ( totalWeight.trim().length() == 0 ) ) ? "" : WEIGHT_MEASUREMENT );
            totalWeight = ( ( ( totalWeight == null )  || ( totalWeight != null && totalWeight.trim().length() == 0 ) ) ? "" : totalWeight );

            String licenseSymbol = commercialInvoiceForm.getLicenseSymbol();
            licenseSymbol = ( ( ( licenseSymbol == null )  || ( licenseSymbol != null && licenseSymbol.trim().length() == 0 ) ) ? "" : licenseSymbol );

            String eccn = commercialInvoiceForm.getEccn();
            eccn = ( ( ( eccn == null )  || ( eccn != null && eccn.trim().length() == 0 ) ) ? "" : eccn );

            totalSalesTaxValue *= salesTaxValue;
            buf.append( "<grandTotal><![CDATA[" + StringUtils.formatAmountWithNoOfDecimals( (salesOrder.getSubTotalAsDouble() )) + "]]></grandTotal>\n" );
            totalSalesTaxValue *= salesTaxValue;

            buf.append ( "<totalPKGS><![CDATA[" + totalPackages +"]]></totalPKGS>\n" );
            buf.append ( "<licenseSymbol><![CDATA[" + licenseSymbol + "]]></licenseSymbol>\n" );
            if (totalWeight.trim().length() == 0 )
            {
                buf.append ( "<totalWeight><![CDATA[]]></totalWeight>\n" );
            }
            else
            {
                buf.append ( "<totalWeight><![CDATA[" + totalWeight + "]]></totalWeight>\n" );
            }
            buf.append ( "<weightMeasurement><![CDATA[" + weightType  + " ]]></weightMeasurement>\n");
            buf.append ( "<weightLabel><![CDATA[" + weightLabel  + " ]]></weightLabel>\n");
            buf.append ( "<eccn><![CDATA[" + eccn + "]]></eccn>\n" );
            buf.append ( "</extInformation>\n" );
            buf.append ( "</commercialInvoice>\n");
        }
        catch(Exception e)
        {
            System.out.println( "Exception while creating the commercial Invoice xml string" );
            e.printStackTrace();
        }

        return buf.toString();
    }

    public static String getCommercialInvoiceAsHtmlFile( String salesOrderIdStr, String customerShippingIdStr, String host ) throws ScalarException
    {

		String MFG_PART_NUMBER_KEY = "";
		String MKT_PART_NUMBER_KEY = "";
		String CUSTOMER_PART_NUMBER_KEY = "";
		String SCHEDULE_NUMBER_KEY	= "";
		String ECCN_NUMBER_KEY	= "";
		String LICENSE_EXCEPTION_KEY	= "";
        String WEIGHT_MEASUREMENT = "";
        String SCHEDULE_NUMBER_DESCRIPTION_KEY = "";
        String COMMERCIAL_INVOICE_NO ="";
        String SIGNATURE ="";
        try
		{
			 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mfgPartNumber");
		}
		catch ( NullPointerException e )
		{
			 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
		}
        try
		{
			 MKT_PART_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mktgPartNumber");
		}
		catch ( NullPointerException e )
		{
			 MKT_PART_NUMBER_KEY = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
		}
		try
		{
			 CUSTOMER_PART_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.customerPartNumber");
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_PART_NUMBER_KEY = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
		}

		try
		{
			SCHEDULE_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ScheduleNumber");
		}
		catch ( NullPointerException e )
		{
			SCHEDULE_NUMBER_KEY = Labels.DEFAULT_SCHEDULE_NUMBER_LABEL;
		}

        try
		{
			SCHEDULE_NUMBER_DESCRIPTION_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ScheduleNumberDiscription");
		}
		catch ( NullPointerException e )
		{
			SCHEDULE_NUMBER_DESCRIPTION_KEY = Labels.DEFAULT_SCHEDULE_NUMBER_DESCRIPTION_LABEL;
		}

        try
		{
			ECCN_NUMBER_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.ECCN");
		}
		catch ( NullPointerException e )
		{
			ECCN_NUMBER_KEY = Labels.DEFAULT_ECCN_NUMBER_LABEL;
		}

		try
		{
			LICENSE_EXCEPTION_KEY = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.commercialInvoice.LicenseSymbol");
		}
		catch ( NullPointerException e )
		{
			LICENSE_EXCEPTION_KEY = Labels.DEFAULT_LICENSE_EXCEPTION_LABEL;
		}

        try
		{
			 WEIGHT_MEASUREMENT = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.WeightMeasurements" );
		}
		catch ( NullPointerException e )
		{
			 WEIGHT_MEASUREMENT = Labels.DEFAULT_WEIGHT_MEASUREMENT_LABEL;
		}
        try
		{
			 COMMERCIAL_INVOICE_NO = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.commercialInvoice.commercialInvoiceNo" );
		}
		catch ( NullPointerException e )
		{
            COMMERCIAL_INVOICE_NO =  "";
        }
        try
		{
			 SIGNATURE = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.signature" );
		}
		catch ( NullPointerException e )
		{
            SIGNATURE =  Labels.DEFAULT_SIGNATURE_LABEL;
        }

        String chipTracContext = "/" + ConfigManager.getChipTracContext();

        int salesOrderId = -1;
        int customerShippingId = -1;
        boolean success = false;

        try
        {
            salesOrderId = Integer.parseInt ( salesOrderIdStr );
            customerShippingId = Integer.parseInt ( customerShippingIdStr );

            success = true;
        }
        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }

        SalesOrder salesOrder = null;
        ArrayList lineItemList = new ArrayList();
        CommercialInvoiceForm commercialInvoiceForm = new CommercialInvoiceForm();
        Address billingAddress = null;
        Address shippingAddress = null;
        Address shipperAddress = null;

        if (success == true)
        {
            Object[] result = getShippedLineItems (salesOrderId, customerShippingId);

            lineItemList = (ArrayList) result[0];

            salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );

            if( salesOrder != null )
            {
                salesOrder.setSubTotalAsDouble(Double.parseDouble((String) result[1]));
                float salesTaxValue = 0.0f;
                salesTaxValue = getSalesTaxValue(salesOrder);
                salesOrder.setSalesTaxValue(salesTaxValue);
            }

            commercialInvoiceForm = CommercialInvoiceDAO.loadCommercialInvoice( customerShippingId );

            if ( commercialInvoiceForm.getBillingId() == -1 )
            {
                 //We are Assigning ShippingFromAddressId to  BillingAddressId because
                //new column called  CST_Billing_Address_Id is added to CST table on 26 May 2004
                //So Previously 'Billing Address' used to get from ShippingFromAddressId DB Field
                //But now we are getting from For CST_Billing_Address_Id DB Field, so prvious PS records we fixed like this
                commercialInvoiceForm.setBillingId(salesOrder.getBillingAddressId());
            }
            commercialInvoiceForm.setBillingAddressObject(CustomerDAO.getAddress( commercialInvoiceForm.getBillingId() ));
            commercialInvoiceForm.setBillingAddress( commercialInvoiceForm.getBillingAddressObject().getAddressAsString () );

			commercialInvoiceForm.setContactPerson ( salesOrder.getShippingAddressAsObject().getContactPerson() );
			// Load the Client Information
			ClientInfo clientInfo = new ClientInfo();
			clientInfo = UserDAO.getClientAddressInfo(  );
			commercialInvoiceForm.setClientName( clientInfo.getClientName() );
            commercialInvoiceForm.setClientInfo( clientInfo );
            commercialInvoiceForm.setCcatsNumber( clientInfo.getCcatsNumber() );
            commercialInvoiceForm.setIsSample( salesOrder.getIsSample());
            commercialInvoiceForm.setShippingVendorAddressObject( VendorDAO.getVendorNameAndAddress( commercialInvoiceForm.getVendorLocationId() ));
            commercialInvoiceForm.setShippingTerms( salesOrder.getShippingTerms() );	

            if( commercialInvoiceForm != null )
            {
                commercialInvoiceForm.setSalesOrderId( salesOrderId );
                shipperAddress = commercialInvoiceForm.getShipperAddressObject();
                billingAddress = commercialInvoiceForm.getBillingAddressObject();
                shippingAddress= commercialInvoiceForm.getShippingAddressObject();
            }
        }

        if( salesOrder == null )
        {
            return null;
        }

        FileWriter fWriter = null;
        BufferedReader bReader = null;
        String filePath = null;

        try
        {
            String mailingTempDir = ConfigManager.getMailerTempDir();
            File tempDir = new File (mailingTempDir).getCanonicalFile();
            tempDir.mkdir();
            tempDir.mkdir();

            String ciAttachmentFileName = commercialInvoiceForm.getPackingSlipNumber();
            if( ( ciAttachmentFileName != null ) && ( ciAttachmentFileName.startsWith( "PS-" ) ) )
            {
                ciAttachmentFileName =  ciAttachmentFileName.substring( 3 );
            }
            ciAttachmentFileName = "Commercial_Invoice_SO_" + ciAttachmentFileName + ".html";

            File ciAttachment = new File( tempDir.getCanonicalPath(), ciAttachmentFileName );
            ciAttachment.deleteOnExit();

            String backgroundImage = "";
            if (Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase (commercialInvoiceForm.getStatus())) {
                backgroundImage = "http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif";
            }

            if( ( ciAttachment.exists() == true ) || ( ciAttachment.createNewFile() == true ) )
            {
                fWriter = new FileWriter (ciAttachment, false);

                fWriter.write( "<HTML><HEAD><TITLE>ChipTrac - Commercial Invoice</TITLE>\n" );
                fWriter.write( "<META http-equiv=Content-Type content='text/html; charset=windows-1252'>\n" );
                fWriter.write( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>\n" );
                fWriter.write( "<BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>\n" );

                fWriter.write( "<table align=center width='100%' border='0'>\n" );
                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='30%' align='left' valign='top'><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/scalar_logo.jpg' height='84' width='200' border=0></td>\n" );
                fWriter.write( "<td width='40%' align=center><font class='NArialW'><u>Commercial Invoice</u></font><br></td>\n" );

                fWriter.write( "<td width='25%' align='right' colspan='2'>\n" );
                fWriter.write( "<table><tr><td align='left' class='NArialL'>");
                fWriter.write( commercialInvoiceForm.getClientName() );
                fWriter.write( commercialInvoiceForm.getClientAddrWithOutEmailObjFormatted() );
                fWriter.write("</td></tr></table>");
                fWriter.write( "</td>\n" );

                /*fWriter.write( "<td width='55%' align=center>&nbsp;</td>\n" );
                fWriter.write( "</tr>\n" );*/
                fWriter.write( "</table>\n" );

                fWriter.write( "<table width='95%' cellspacing='0' cellpadding='0' border=0 background='"+backgroundImage+"' align=center>\n" );

                fWriter.write( "<tr height=30>\n" );
                fWriter.write( "<td width='34%' class='NArialL' bgcolor='#DEE1E2' >&nbsp;Shipper :</td>\n" );
                fWriter.write( "<td width='1%'><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif'></td>\n" );
                fWriter.write( "<td width='30%' class='NArialL' bgcolor='#DEE1E2' >&nbsp;Bill To :</td>\n" );
                fWriter.write( "<td width='1%'><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif'></td>\n" );
                fWriter.write( "<td width='34%'  bgcolor='#DEE1E2'><font class='NArialL'>&nbsp;Ship To :</font></td>\n" );
                fWriter.write( "</tr>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='34%' bgcolor='#FFFFEE' class='NArialS' valign='top'>\n" );
                fWriter.write( "<table width='100%' class='NArialS'>\n" );

                fWriter.write( "<tr><td>" /*+ commercialInvoiceForm.getClientName() + " c/o "*/ + ( ( commercialInvoiceForm.getClientName() == null) ? "" : commercialInvoiceForm.getClientName() ) + "<br>\n" );

                fWriter.write( commercialInvoiceForm.getShipperVendorAddressAsHTML() );  //Added by Krishna Prasad on 27 May 2004
                fWriter.write( "</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td>\n" );

                fWriter.write( "<td width='1%'><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif'></td>\n" );
                fWriter.write( "<td width='34%' bgcolor='#FFFFEE' class='NArialS' valign='top'>\n" );
                fWriter.write( "<table width='100%' class='NArialS'><tr><td> \n" );

                //fWriter.write( commercialInvoiceForm.convertAddressObjToHtml ( billingAddress, salesOrder.getCustomerName() ) );
                fWriter.write( billingAddress.getAddressAsHTML() );
                fWriter.write( "</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td>\n" );
                fWriter.write( "<td width='1%'><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif'></td>\n" );

                fWriter.write( "<td width='34%' bgcolor='#FFFFEE' class='NArialS' valign='top'>\n" );
                fWriter.write( "<table width='100%' class='NArialS'><tr><td> \n" );

                //fWriter.write( commercialInvoiceForm.convertAddressObjToHtml ( shippingAddress, salesOrder.getCustomerName() ) );
                fWriter.write( shippingAddress.getAddressAsHTML() );
                fWriter.write( "</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=20></td></tR>\n" );

                fWriter.write( "<tr><td class='NArialS' colspan='5'>\n" );
                fWriter.write( "<table width='100%' border='0'>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>");

                if( commercialInvoiceForm.getIsSample())
                {
                    fWriter.write("Sample Sales Order# :</td>\n" );
                }
                else
                {
                    fWriter.write("Sales Order# :</td>\n" );
                }

                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + salesOrder.getSalesOrderNo() + "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialL' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Packing Slip#&nbsp;:</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + commercialInvoiceForm.getPackingSlipNumber() + "</td>\n" );
                fWriter.write( "</tr>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>" + COMMERCIAL_INVOICE_NO + " :" + "</td>");
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + commercialInvoiceForm.getCommercialInvoiceNo() + "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialL' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'></td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'></td>\n" );
                fWriter.write( "</tr>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Ship Date :</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" );
                if ( commercialInvoiceForm.getShipDate() != null )
                {
					fWriter.write( commercialInvoiceForm.getShipDate() );
                }
				fWriter.write( "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialS' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Payment Terms</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>");
                fWriter.write( commercialInvoiceForm.getShippingTerms() );
                fWriter.write( "</td>\n");
                fWriter.write( "</tr>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Way Bill :</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" );
                if ( commercialInvoiceForm.getFrieghtTrackingNumber() != null && commercialInvoiceForm.getFrieghtTrackingNumber().length >= 1 )
                {
					fWriter.write( commercialInvoiceForm.getFrieghtTrackingNumber()[0] );
                }
				fWriter.write( "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialS' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Customer P.O. #&nbsp;:</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + ( ( ( salesOrder.getCustomerPO() == null ) || ( salesOrder.getCustomerPO().trim().length() == 0 ) ) ? "&nbsp;" : salesOrder.getCustomerPO() + "</td>\n") );
                fWriter.write( "</tr>\n" );

				if ( commercialInvoiceForm.getFrieghtTrackingNumber() != null && commercialInvoiceForm.getFrieghtTrackingNumber().length > 1 )
				{
					for ( int i = 0; i < commercialInvoiceForm.getFrieghtTrackingNumber().length - 1; i++ )
					{
						fWriter.write( "<tr>\n" );
						fWriter.write( "<td width='20%' class='NArialL' align='left'>&nbsp;</td>\n" );
						fWriter.write( "<td width='25%'  class='NArialS' align='left'>" );
						fWriter.write( commercialInvoiceForm.getFrieghtTrackingNumber()[i + 1] );
						fWriter.write( "</td>\n" );
						fWriter.write( "<td width='10%' class='NArialS' align='right'>&nbsp;</td>\n" );
						fWriter.write( "<td width='20%' class='NArialL' align='right'></td>\n" );
						fWriter.write( "<td width='25%'  class='NArialS' align='left'>&nbsp;</td>\n" );
						fWriter.write( "</tr>\n" );
					}
				}

                String deliveryTerms = commercialInvoiceForm.getFob();
                deliveryTerms = ( ( ( deliveryTerms == null )  || ( deliveryTerms.trim().length() == 0 ) ) ? "&nbsp;" : deliveryTerms );

                String fabOriginCountry = commercialInvoiceForm.getCountryOfFabOrigin();
                fabOriginCountry = ( ( ( fabOriginCountry == null )  || ( fabOriginCountry.trim().length() == 0 ) ) ? "&nbsp;" : fabOriginCountry );

                String assyOriginCountry = commercialInvoiceForm.getCountryOfAssyOrigin();
                assyOriginCountry = ( ( ( assyOriginCountry == null )  || ( assyOriginCountry.trim().length() == 0 ) ) ? "&nbsp;" : assyOriginCountry );


                /*String landingPort = commercialInvoiceForm.getPortOfLanding();
                landingPort = ( ( ( landingPort == null )  || ( landingPort.trim().length() == 0 ) ) ? "&nbsp;" : landingPort );

                String destinationPort = commercialInvoiceForm.getPortOfDestination();
                destinationPort = ( ( ( destinationPort == null )  || ( destinationPort.trim().length() == 0 ) ) ? "&nbsp;" : destinationPort );
                */
                String comments = commercialInvoiceForm.getComments();
				comments = ( ( ( comments == null )  || ( comments.trim().length() == 0 ) ) ? "&nbsp;" : comments );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>INCOTERMS:</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + deliveryTerms + "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialS' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Country of Origin(Fab):</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + fabOriginCountry + "</td>\n" );
                fWriter.write( "</tr>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='10%' class='NArialS' align='left'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Country of Origin(Assy):</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + assyOriginCountry + "</td>\n" );
                fWriter.write( "</tr>\n" );


                /*fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='left'>Loading Port:</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + landingPort + "</td>\n" );
                fWriter.write( "<td width='10%' class='NArialS' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='right'>Destination Port&nbsp;:</td>\n" );
                fWriter.write( "<td width='25%'  class='NArialS' align='left'>" + destinationPort + "</td>\n" );
                fWriter.write( "</tr>\n" );*/
                fWriter.write( "</table>\n" );
                fWriter.write( "</td></tr>\n" );

				fWriter.write( "<tr><td colspan='5' class='NArialL' align='left'>Comments&nbsp;:</td></tr>\n" );
				fWriter.write( "<tr><td colspan='5' class='NArialS' align='left'>\n");
				fWriter.write( comments );
				fWriter.write( "</td></tr>\n" );

                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=20></td></tR>\n" );

                fWriter.write( "<tr><td colspan='5'>\n" );
                fWriter.write( "<table width='100%' border=1 cellpadding='0' cellspacing='0' bordercolor='#000000'>\n" );
                fWriter.write( "<tr height=30>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>PO Line Number</td>\n" );
				fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ MKT_PART_NUMBER_KEY +"</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ CUSTOMER_PART_NUMBER_KEY +"</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Product <br>Description</td>\n" );
				fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Units</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ SCHEDULE_NUMBER_KEY +"</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ SCHEDULE_NUMBER_DESCRIPTION_KEY +"</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ ECCN_NUMBER_KEY +"</td>\n" );
				fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>"+ LICENSE_EXCEPTION_KEY +"</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Shipped Qty</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Unit<br>Price <br> (USD)</td>\n" );
                fWriter.write( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Line<br>Total</td>\n" );
                fWriter.write( "</tr>\n" );

                float totalSalesTaxValue = 0f;
                float salesTaxValue = salesOrder.getSalesTaxValue();

                if( ( lineItemList != null ) && ( lineItemList.size() != 0 ) )
                {
                    int lineItemListSize = lineItemList.size();
                    LineItem lineItem = null;

                    int poLineItem = -1;
                    String mktPartNumber = null;
                    String mfgPartNumber = null;
					String custPartNumber = null;
                    String description = null;
                    String scheduleNumber = null;
                    String qty = null;
                    String unitPrice = null;
                    String amount = null;

                    for( int i = 0; i <= ( lineItemListSize-1 ); i++ )
                    {
                        lineItem = ( LineItem ) lineItemList.get( i );

                        poLineItem = lineItem.getPoLineItemNo();

                        if(lineItem.getIsTaxable()){
                            totalSalesTaxValue += lineItem.getAmount();
                        }

                        mfgPartNumber = lineItem.getManufacturingPartNo();
                        mktPartNumber = lineItem.getMarketingPartNo();
                        if( ( mktPartNumber == null ) || ( mktPartNumber.trim().length() == 0 ) ) { mktPartNumber = "&nbsp;"; }
                        if( ( mfgPartNumber == null ) || ( mfgPartNumber.trim().length() == 0 ) ) { mfgPartNumber = "&nbsp;"; }

						custPartNumber = lineItem.getCustomerPartNumber();
                        if( ( custPartNumber == null ) || ( custPartNumber.trim().length() == 0 ) ) { custPartNumber = "&nbsp;"; }

                        description = lineItem.getDescription();
                        if( ( description == null ) || ( description.trim().length() == 0 ) ) { description = "&nbsp;"; }

                        scheduleNumber = lineItem.getScheduleNumber();
                        if( ( scheduleNumber == null ) || ( scheduleNumber.trim().length() == 0 ) ) { scheduleNumber = "&nbsp;"; }

                        qty = lineItem.getQtyAsString();
                        if( ( qty == null ) || ( qty.trim().length() == 0 ) ) { qty = "&nbsp;"; }

                        amount = lineItem.getAmountAsString();
                        if( ( amount == null ) || ( amount.trim().length() == 0 ) ) { amount = "&nbsp;"; }

                        unitPrice = lineItem.getDisplayUnitPrice();
                        if( ( unitPrice == null ) || ( unitPrice.trim().length() == 0 ) ) { unitPrice = "&nbsp;"; }

                        fWriter.write( "<tr height=30>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>" + ( poLineItem < 1 ? "" : poLineItem+"" ) + "</td>\n" );

                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=left nowrap>&nbsp;" + mktPartNumber + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=left nowrap>&nbsp;" + custPartNumber + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=left width=240>&nbsp;" + description + "</td>\n" );
						fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>&nbsp;" + ( lineItem.getUom() != null ? lineItem.getUom() : "&nbsp;" ) + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>&nbsp;" + Constants.COMMERCIAL_INVOICE_HTS_CODE + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>&nbsp;" + Constants.COMMERCIAL_INVOICE_HTS_DESCRIPTION + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>&nbsp;" + Constants.COMMERCIAL_INVOICE_ECCN + "</td>\n" );
						fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=center nowrap>&nbsp;" + ( lineItem.getLicenseException() != null ? lineItem.getLicenseException() : "&nbsp;" ) + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=right nowrap>&nbsp;" + qty + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=right nowrap>&nbsp;" + unitPrice + "</td>\n" );
                        fWriter.write( "<td bgcolor='#FFFFEE' class='NArialS' align=right nowrap>&nbsp;" + amount + "</td>\n" );
                        fWriter.write( "</tr>\n" );

                    }   // for loop

                }   // if loop

                String totalPackages = commercialInvoiceForm.getTotalPackagesStr()+"";
                totalPackages = ( ( ( totalPackages == null )  || ( totalPackages.trim().length() == 0 ) ) ? "&nbsp;" : totalPackages );

                String totalWeight  = commercialInvoiceForm.getTotalWeight()+"";
                String weightType   = commercialInvoiceForm.getWeightType();

                WEIGHT_MEASUREMENT = ( ( ( totalWeight == null )  || ( totalWeight.trim().length() == 0 ) ) ? "&nbsp;" : WEIGHT_MEASUREMENT );
                totalWeight = ( ( ( totalWeight == null )  || ( totalWeight.trim().length() == 0 ) ) ? "&nbsp;" : totalWeight );



                String licenseSymbol = commercialInvoiceForm.getLicenseSymbol();
                licenseSymbol = ( ( ( licenseSymbol == null )  || ( licenseSymbol.trim().length() == 0 ) ) ? "&nbsp;" : licenseSymbol );

                String eccn = commercialInvoiceForm.getEccn();
                eccn = ( ( ( eccn == null )  || ( eccn.trim().length() == 0 ) ) ? "&nbsp;" : eccn );

                fWriter.write( "<tr><td colspan='11' align=center ><font class='NArialS'><br>NOTE: THE VALUE SHOWN IS FOR CUSTOMS PURPOSE ONLY.</font></td></tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td></tr>\n" );
                fWriter.write( "<tr><td colspan=5 bgcolor='#DEE1E2' align='right'><font class='NArialL'>\n" );
                totalSalesTaxValue *= salesTaxValue;
                fWriter.write( "Grand Total: " + StringUtils.formatAmountWithNoOfDecimals( (salesOrder.getSubTotalAsDouble() /*+ totalSalesTaxValue + salesOrder.getFrieght() + salesOrder.getMisc()*/)) + " </font></td></tR>\n" );
                totalSalesTaxValue *= salesTaxValue;
                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=20></td></tR>\n" );
                fWriter.write( "<tr><td colspan=5>\n" );
                fWriter.write( "<table width='100%' border='0'>\n" );
                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='right'>TOTAL PKGS:</td>\n" );
                fWriter.write( "<td width='5%'  class='NArialS' align='center'>" + totalPackages +"</td>\n" );
                fWriter.write( "<td width='5%' class='NArialS' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='45%' class='NArialS' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='5%'  class='NArialS' align='left' nowrap>&nbsp;</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "<tr>\n" );
                if( ConfigManager.getShowPackageDimensionInPackingSlip() )
                {
                    fWriter.write( "<td width='20%' class='NArialL' align='right'>NET WEIGHT:</td>\n" );
                }
                else
                {
                    fWriter.write( "<td width='20%' class='NArialL' align='right'>WEIGHT:</td>\n" );
                }
                fWriter.write( "<td width='5%'  class='NArialS' align='center'>" + totalWeight + "</td>\n" );
                //fWriter.write( "<td width='5%' class='NArialL' align='right'>&nbsp;&nbsp;(Lbs)</td>\n" );
                fWriter.write( "<td width='5%' class='NArialL' align='right'>&nbsp;&nbsp;"+ weightType + "</td>\n" );
                fWriter.write( "<td width='45%' class='NArialS' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='20%' class='NArialL' align='right'>&nbsp;</td>\n" );
                fWriter.write( "<td width='5%'  class='NArialS' align='left' nowrap>&nbsp;</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td></tr>\n" );

                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=20></td></tR>\n" );

                fWriter.write( "<tr><td colspan=5>\n" );
                fWriter.write( "<table width='100%' cellpadding='0' cellspacing='0' border='1' bordercolor='#000000' class='NArialS'>\n" );
                fWriter.write( "<tr><td>\n" );
                fWriter.write( "These commodities, technology, or software were exported from the United States in accordance<br>\n" );
                fWriter.write( "with the Export Administration regulations. Diversion contrary to U.S. law is prohibited.\n" );
                fWriter.write( "</td></tr>\n" );
                fWriter.write( "</table>\n" );
                fWriter.write( "</td></tr>\n" );

                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=25></td></tR>\n" );

                fWriter.write( "<tr>\n" );
                fWriter.write( "<td colspan='5'>\n" );

                fWriter.write( "<table border='0' width='100%'>\n" );
                fWriter.write( "<tr>\n" );
                fWriter.write( "<td width='15%' class='NArialL' align=center valign=bottom>Signature:</td>\n" );
                fWriter.write( "<td width='50%' class=signatureGray align=left>&nbsp;&nbsp;&nbsp;&nbsp;\n" );
                fWriter.write( SIGNATURE );
                fWriter.write( "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n" );
                fWriter.write( "<td width='5%' align=center>&nbsp;</td>\n" );
                fWriter.write( "<td width='10%' class='NArialL' align=center valign=bottom>Date:</td> \n" );
                fWriter.write( "<td width='20%' class=signature align=center>&nbsp;</td>\n" );
                fWriter.write( "</tr>\n" );
                fWriter.write( "</table>\n");

                fWriter.write( "</td></tr>\n");
                fWriter.write( "<tr><td colspan=5><img src='http://" + host + "/" + chipTracContext + "/jsp/includes/images/spacer.gif' height=25></td></tR>\n");
                fWriter.write( "</table></body></html>\n");

                fWriter.flush();

                filePath = ciAttachment.getAbsolutePath();
            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating HTML view of the commercial Invoice" );
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }

            if( bReader != null )
            {
                try { bReader.close(); } catch( IOException ignore ) {}
            }
        }

        return filePath;
    }

    // added by hareesh on 31st July 2003
    // -- START --
    // In DataBase there are four types of values Sales Tax values are present
    // 1) sales_tax_table Table State value
    // 2) 0 if salesTax is not selected
    // 3) null for some records
    // 4) 0.0825 for some records
	public static float getSalesTaxValue( SalesOrder salesOrder )
    {
    	String salesTaxType = salesOrder.getSalesTaxType();
        float salesTax 		= 0.0f;

        try
        {
			if( salesTaxType != null && salesTaxType.trim().length() != 0 )
			{
            	if( SalesOrderDAO.doesSalesTaxStateExist( null, salesOrder.getSalesTaxType() ) )
            	{
                	salesTax = SalesOrderDAO.getTaxValue( null, salesTaxType );
                    salesTax /= 100;
                }
                else
                {
                	try
                	{
                    	salesTax = Float.parseFloat(salesTaxType.trim());
                    }
                    catch( Exception ex )
                    {
                    	salesTax = 0.0f;
                    }
                }
            }
            else
            {
            	salesTax = 0.0f;
            }
        }
        catch( Exception ex )
        {
        	salesTax = 0.0f;
        }
        return salesTax;
    }

    // -- END --
    /**
     * @return temporary html file absolute path
    /////////////////////Balaram///////June/////27////////////////////////////////////////////////
    // OLD VERSION // TO BE USED LATER // DO NOT DELETE //////////////////////////////////////////

    public static String getCommercialInvoiceAsHtmlFile( String salesOrderId, String customerShippingId, String host)
    {
        FileWriter fWriter = null;
        BufferedReader bReader = null;
        String filePath = null;

        try
        {
            File tempDir = new File ("chiptrac_temp_dir").getCanonicalFile();
            tempDir.mkdir();

            File ciAttachment = new File (tempDir.getCanonicalPath(), "Commercial_Invoice_" + System.currentTimeMillis() + ".html");
            ciAttachment.deleteOnExit();

            if( ( ciAttachment.exists() == true ) || ( ciAttachment.createNewFile() == true ) )
            {
                URL url = new URL( "http://" + host + "/" + ConfigManager.getChipTracContext() + COMMERCIAL_INVOICE_MAIL_FORMAT_PAGE + "?salesOrderId=" + salesOrderId + "&customerShippingId=" + customerShippingId );
                bReader = new BufferedReader ( new InputStreamReader ( url.openStream() ) );

                fWriter = new FileWriter (ciAttachment, false);
                String line = null;

                while( ( line = bReader.readLine() ) != null )
                {
                    fWriter.write( line );
                }

                try {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ) {}

                filePath = ciAttachment.getAbsolutePath();
            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating HTML view of the commercial Invoice" );
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }

            if( bReader != null )
            {
                try { bReader.close(); } catch( IOException ignore ) {}
            }
        }

        return filePath;
    }

    // OLD VERSION // TO BE USED LATER // DO NOT DELETE //////////////////////////////////////////
    /////////////////////Balaram///////June/////27///////////////////////////////////////////////*/
    private static Object[] adjustLineItemPrice ( ArrayList resultLineItems, int zeroPriceTotalQty, double grandTotal ) throws ScalarException
    {
        HashMap commercialSettings = CommercialInvoiceDAO.loadCommercialInvoiceSettings();
    	String flag = (String)commercialSettings.get( "Adjust_Flag" );
		LineItem lineItem = null;
        float min_unit_price  = 0.0f;
        if( commercialSettings.get("Min_Unit_Price") != null )
        {
		    min_unit_price 	= ((Float)commercialSettings.get("Min_Unit_Price")).floatValue();
        }
        float min_Grand_Total = 0.0f;
        if ( commercialSettings.get ( "Min_Grand_Total" ) != null )
        {
            min_Grand_Total = ((Float)commercialSettings.get("Min_Grand_Total")).floatValue();
        }
        float subTotal = 0.0f;
    	if( "1".equals( flag ) )
    	{
            double price = min_unit_price;
            if ( grandTotal < min_Grand_Total )
            {
                price = ((min_Grand_Total-grandTotal)/(double)zeroPriceTotalQty);
                if ( price < min_unit_price )
                {
                    price = min_unit_price;
                }
            }

            for ( int i = 0; i < resultLineItems.size(); i++ )
    		{
				lineItem = (LineItem)resultLineItems.get(i);
				lineItem.getQuantity();
				lineItem.getUnitPriceAsDouble();
				lineItem.getAmount();

				if( lineItem.getUnitPriceAsDouble() == 0 && lineItem.getQuantity() > 0 )
				{
                    lineItem.setUnitPriceAsDouble( price );
                    lineItem.setAmountAsDouble( lineItem.getUnitPriceAsDouble() * lineItem.getQuantity() );
                }
                subTotal +=  lineItem.getUnitPriceAsDouble() * lineItem.getQuantity();
            }
        }
        return new Object[]{resultLineItems, subTotal+""};
    }
}